package com.hunter.desktop.file.mapping;

import java.util.Date;


import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.DateTools.Resolution;

import com.hunter.desktop.file.FileData;
import com.hunter.lucene.util.mapping.Mapper;
import static com.hunter.desktop.file.FieldNameConstants.*;


/**
 * 
 * @author bastengao
 *
 */

public class FileMapper implements Mapper<FileData> {

	@Override
	public Document indexMap(FileData e) {
		/**
		 * 应该对不同的属性设置不同的权重。比如标题的权重要比内容的权重高。 这样搜索匹配度高的才能排在前面
		 */
		Field fileName = new Field(NAME, e.getFileName(), Field.Store.YES,
				Field.Index.NOT_ANALYZED);

		Field fileNameAnalyzed = new Field(NAME_ANALYZED, e.getFileName(),
				Field.Store.YES, Field.Index.ANALYZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);

		Field absolutePath = new Field(ABSOLUTE_PATH, e.getAbsolutePath(),
				Field.Store.YES, Field.Index.NOT_ANALYZED);

		Field absolutePathAnalyzed = new Field(ABSOLUTE_PATH_ANALYZED, e
				.getAbsolutePath(), Field.Store.YES, Field.Index.ANALYZED,
				Field.TermVector.WITH_POSITIONS_OFFSETS);

		Field lastModifiedLong = new Field(LAST_MODIFY_LONG, String.valueOf(e
				.getLastModified()), Field.Store.YES, Field.Index.NO);

		Field lastModifiedDate = new Field(LAST_MODIFY_DATE,
				DateTools.dateToString(new Date(e.getLastModified()),
						Resolution.MINUTE), Field.Store.YES,
				Field.Index.ANALYZED);

		Field isHidden = new Field(IS_HIDDEN, Boolean.toString(e.isHidden()),
				Field.Store.YES, Field.Index.NO);

		Document document = new Document();
		document.add(fileName);
		document.add(fileNameAnalyzed);
		document.add(absolutePath);
		document.add(absolutePathAnalyzed);
		document.add(lastModifiedLong);
		document.add(lastModifiedDate);
		document.add(isHidden);

		return document;
	}

	public FileData searchMap(FileData file, Document document) {

		String name = document.getField(NAME).stringValue();
		file.setFileName(name);

		String path = document.getField(ABSOLUTE_PATH).stringValue();
		file.setAbsolutePath(path);

		String lastModifiedStr = document.getField(LAST_MODIFY_LONG)
				.stringValue();
		long lastModified = Long.parseLong(lastModifiedStr);
		file.setLastModified(lastModified);

		boolean isHidden = Boolean.valueOf(document.getField(IS_HIDDEN)
				.stringValue());
		file.setHidden(isHidden);

		return file;
	}

	@Override
	public FileData searchMap(Document document) {
		throw new UnsupportedOperationException();
	}

}
